﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.ServiceProcess;

namespace InstallAttendanceWindowsService
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public string serviceName = "AttendanceService";
        private void button1_Click(object sender, EventArgs e)
        {
            string[] args = { "AttendanceWindowsService.exe" };//要安装的服务文件（就是用 InstallUtil.exe 工具安装时的参数）  
            ServiceController svcCtrl = new ServiceController(serviceName);
            if (!ServiceIsExisted(serviceName))
            {
                try
                {
                    System.Configuration.Install.ManagedInstallerClass.InstallHelper(args);
                    MessageBox.Show("服务安装成功！");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
            else
            {
                MessageBox.Show("该服务已经存在，不用重复安装。");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (ServiceIsExisted(serviceName))
                {
                    //UnInstall Service  
                    System.Configuration.Install.AssemblyInstaller myAssemblyInstaller = new System.Configuration.Install.AssemblyInstaller();
                    myAssemblyInstaller.UseNewContext = true;
                    myAssemblyInstaller.Path = "AttendanceWindowsService.exe";
                    myAssemblyInstaller.Uninstall(null);
                    myAssemblyInstaller.Dispose();
                    MessageBox.Show("卸载服务成功！");
                }
                else
                {
                    MessageBox.Show("服务不存在！");
                }

            }
            catch (Exception)
            {
                MessageBox.Show("卸载服务失败！");
            }
        }

        /// <summary>  
        /// 检查指定的服务是否存在  
        /// </summary>  
        /// <param name="serviceName">要查找的服务名字</param>  
        /// <returns></returns>  
        private bool ServiceIsExisted(string svcName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.ServiceName == svcName)
                {
                    return true;
                }
            }
            return false;
        }
    }
}